package nio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ReadAndWriteOneLine {

	public static void main(String[] args) {
		File filein = new File("file/linein.txt");
		File fileout = new File("file/lineout-nio.txt");
		try {
			RandomAccessFile fin = new RandomAccessFile(filein, "r");
			FileChannel inChannel = fin.getChannel();
			
			ByteBuffer buf = ByteBuffer.allocate(48);
			
			int bytesRead = inChannel.read(buf);
			String content="";
			while(bytesRead != -1){
				buf.flip();
				byte a[] = new byte[buf.remaining()];
				buf.get(a);
				content += new String(a);
				buf.clear();
				bytesRead = inChannel.read(buf);	
			}
			fin.close();
			content = content.replace("\n", "").replace("\r", "");
			
			FileOutputStream fout = new FileOutputStream(fileout);
			FileChannel outChannel = fout.getChannel();
			ByteBuffer bufout = ByteBuffer.allocate(4*content.length());
			bufout.put(content.getBytes());
			bufout.flip();
			outChannel.write(bufout);
			fout.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
